package com.example.codefilter.framework.security.filter;

import cn.hutool.core.util.StrUtil;
import com.example.codefilter.common.constant.HttpMethod;
import com.example.codefilter.common.exception.ValidateCodeException;
import com.example.codefilter.framework.security.handle.LoginFailureHandler;
import com.google.code.kaptcha.Constants;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.time.LocalDateTime;


/**
 * 自定义验证代码过滤
 *
 * @author LiJunYi
 * @date: 2022/07/27
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter
{

    @Resource
    private LoginFailureHandler authenticationFailure;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String loginUrl = "/userLogin";
        if (loginUrl.equalsIgnoreCase(request.getRequestURI())
                && HttpMethod.POST.equalsIgnoreCase(request.getMethod())) {
            try {
                HttpSession session = request.getSession();
                // Session中的校验码
                String sessionImgCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
                // Session 中校验码过期时间
                LocalDateTime expireTime = (LocalDateTime) session.getAttribute(Constants.KAPTCHA_SESSION_DATE);
                // 客户端提交的校验码
                String requestImgCode = request.getParameter(com.example.codefilter.common.constant.Constants.CAPTCHA_CODE);
                if (StrUtil.isEmpty(requestImgCode)) {
                    throw new ValidateCodeException("验证码不能为空！");
                }
                if (expireTime == null || LocalDateTime.now().isAfter(expireTime)) {
                    // 清除Session中校验码相关信息
                    session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
                    session.removeAttribute(Constants.KAPTCHA_SESSION_DATE);
                    throw new ValidateCodeException("验证码已过期！");
                }
                if (!requestImgCode.equalsIgnoreCase(sessionImgCode)) {
                    throw new ValidateCodeException("验证码不正确！");
                }
                // 清除Session中校验码相关信息
                session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
                session.removeAttribute(Constants.KAPTCHA_SESSION_DATE);
            } catch (ValidateCodeException e) {
                authenticationFailure.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
